package cn.waxcc.controller;

import cn.waxcc.pojo.Commodity;
import cn.waxcc.utils.RedisUtil1;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;

/**
 * 功能说明
 *
 * @author HZ
 * @date 2023-04-25 09:08:49
 */
@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private RedisUtil1 redisUtil1;
    //选用商品添加到购物车
    @ApiOperation(value="选用设备添加到购物车")
    @PostMapping("/addGoodsToCart")
    public boolean addGoodsToCart(Integer uId, Commodity commodity){
        boolean hsetSuccessStatus = redisUtil1.hset("user:"+uId, commodity.getId(), commodity);
        System.out.println("user:"+uId);
        System.out.println(commodity);
        return hsetSuccessStatus;
    }
    // 从购物车缓存中取数据
    @ApiOperation(value = "从购物车缓存中取数据")
    @GetMapping("/getEquipmentInCartByUserId")
    public ArrayList<Commodity> getEquipmentInCartByUserId(Integer uId) {

        Commodity goodShopcar;

        Map<Object, Object> userCartItems = redisUtil1.hgetall("user:"+uId);
        System.out.println("user:"+uId);
        System.out.println(userCartItems);
        ArrayList<Commodity> cartItemVos = new ArrayList<>();

        //遍历map中的值 每一个value都是一个goodShopcar对象
        for (Object value : userCartItems.values()) {
            System.out.println(value);

            goodShopcar = (Commodity) value;

            cartItemVos.add(goodShopcar);
        }
        return cartItemVos;
    }

    // 修改
    @ApiOperation(value = "修改购物车数据")
    @PutMapping("/updateGoodsToCart")
    public Boolean updateEquipmentToCart(Integer uId, Commodity goodShopcar) {

        boolean hsetSuccessStatus = redisUtil1.hset("user:"+uId, goodShopcar.getId(), goodShopcar);
        System.out.println("user:"+uId);
        System.out.println(goodShopcar);
        return hsetSuccessStatus;
    }

    // 删除
    @ApiOperation(value = "选用设备从购物车删除")
    @DeleteMapping("{uId}/{gId}")
    public Boolean DeleteEquipmentFromCart(@PathVariable String uId, @PathVariable String gId) {

        boolean b = redisUtil1.hHasKey("user:" + uId, gId);

        System.out.println(b);

        if (b){
            redisUtil1.hdel("user:"+uId, gId);
        }
        return b;
    }
}
